import type { FetchRequest, FetchOptions } from 'ohmyfetch'
import { $fetch } from 'ohmyfetch'
import { IApiBase } from '~~/types/api'
import {message} from 'ant-design-vue'
export const BASE_URL = 'http://127.00.0.1:8081/api'
// const BASE_URL = 'https://backend-course.xiaoping.fun/api'

const _useApi = $fetch.create({
    baseURL: BASE_URL,
    async onRequest({ options }) {
        const { token } = $(useUser());
        options.headers = new Headers(options.headers);
        if(token) options.headers.set('authorization', token)
    },
    async onResponse({ response }) {
        let data = response._data
        if(data?.code !==0) {
            if (data.code === 270004) return;
            return message.error(data.msg || '请求失败')
        }
        
    }
})
export const useApi = async<T = any>(request: FetchRequest, opinion?: FetchOptions<"json">) => {
    try {
        return await _useApi<IApiBase<T>>(request, opinion)
    } catch (error) {
        return error
    }
}


